package com.ridaizu.bean;

import java.io.Serializable;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.LazyDataModel;

import com.google.common.base.Strings;
import com.ridaizu.cache.CacheDataBean;
import com.ridaizu.dao.db.DBManager;
import com.ridaizu.lazy.LazyInventoryDataModel;
import com.ridaizu.model.Inventory;
import com.ridaizu.model.form.InventoryForm;
import com.ridaizu.model.search.InventorySearch;
import com.ridaizu.service.impl.InventoryServiceImpl;
import com.ridaizu.util.DateUtil;

@javax.faces.bean.ManagedBean(name = "inventoryBean")
@SessionScoped
public class InventoryBean implements Serializable {

	private static final long serialVersionUID = 1L;

	private LazyDataModel<Inventory> lazyModel;

    @ManagedProperty("#{cacheDataBean}")
    private CacheDataBean cacheDataBean;

    @ManagedProperty("#{inventoryServiceImpl}")
    private InventoryServiceImpl inventoryService;

    @ManagedProperty("#{inventorySearch}")
    private InventorySearch inventorySearch;

    @ManagedProperty("#{inventoryForm}")
    private InventoryForm inventoryForm;

	public void searchInventorySync() {
		lazyModel = new LazyInventoryDataModel(inventorySearch);
	}

	public void viewRegisterInventory() throws SQLException {

		setInitValues(null);

        Map<String,Object> options = new HashMap<String, Object>();
        options.put("modal", true);
        options.put("contentWidth", 550);
        options.put("contentHeight", 200);

        RequestContext.getCurrentInstance().openDialog("inventory", options, null);
    }

	public void viewUpdateInventory(Inventory inventory) throws SQLException {

		setInitValues(inventory);

        Map<String,Object> options = new HashMap<String, Object>();
        options.put("modal", true);
        options.put("contentWidth", 550);
        options.put("contentHeight", 220);

        RequestContext.getCurrentInstance().openDialog("inventory", options, null);
    }

	private void setInitValues(Inventory inventory) throws SQLException {
		inventoryForm.clearAll();
		setValues(inventory);
	}

	private void setValues(Inventory inventory) {
		if (inventory == null) {
			setRegisterValues();
		} else {
			setUpdateValues(inventory);
		}
	}

	private void setRegisterValues() {
	}

	private void setUpdateValues(Inventory inventory) {
		inventoryForm.setId(String.valueOf(inventory.getId()));
		inventoryForm.setGoodsId(String.valueOf(inventory.getGoodsId()));
		inventoryForm.setCount(String.valueOf(inventory.getCount()));
		inventoryForm.setRgtOpt(inventory.getRgtOpt());
		inventoryForm.setRgtDate(new Date(inventory.getRgtDate().getTime()));
		inventoryForm.setUpdOpt(inventory.getUpdOpt());
		inventoryForm.setUpdDate(new Date(inventory.getUpdDate().getTime()));
	}

	public void registerInventory() {
		Inventory inventory = getInventory();

		boolean result = false;

		try {
			DBManager.beginTransaction();
			result = inventoryService.insertModel(inventory);
			DBManager.commitTransaction();

		} catch (SQLException e) {
			e.printStackTrace();
			result = false;
			DBManager.rollbackTransaction();
		}

		RequestContext.getCurrentInstance().closeDialog(result);
    }

	public void updateInventory() {

		Inventory inventory = getInventory();

		boolean result = false;

		try {
			DBManager.beginTransaction();
			result = inventoryService.updateModel(inventory);
			DBManager.commitTransaction();

		} catch (SQLException e) {
			e.printStackTrace();
			result = false;
			DBManager.rollbackTransaction();
		}

		RequestContext.getCurrentInstance().closeDialog(result);
	}

	public void deleteInventory() {

		Inventory selectedInventory = inventoryForm.getSelectedInventory() ;

		if (selectedInventory == null || selectedInventory.getId() < 1) {
	        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Message", "请选择要删除的库存信息。");
	        FacesContext.getCurrentInstance().addMessage(null, message);

	        return ;
		}

		boolean result = false;
		try {
			DBManager.beginTransaction();
			result = inventoryService.deleteModel(selectedInventory.getId());
			DBManager.commitTransaction();
		} catch (SQLException e) {
			e.printStackTrace();
			result = false;
			DBManager.rollbackTransaction();
		}

		String resultStr = null;
		if (result) {
			resultStr = String.format("库存[%s]删除成功。", selectedInventory.getId());
		} else {
			resultStr = String.format("库存[%s]删除失败。", selectedInventory.getId());
		}

        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Inventory delete result", resultStr);
        FacesContext.getCurrentInstance().addMessage(null, message);
	}

	public void registerInventoryResult(SelectEvent event) {
		boolean result = (Boolean) event.getObject();

		handleResult(result, "登录");
	}

	public void updateInventoryResult(SelectEvent event) {

		boolean result = (Boolean) event.getObject();

		handleResult(result, "更新");
	}

	private void handleResult(boolean result, String optStr) {

		String resultStr = null;
		if (result) {
			resultStr = String.format("库存信息%s成功。", optStr);
		} else {
			resultStr = String.format("库存信息%s失败。", optStr);;
		}

        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Message", resultStr);

        FacesContext.getCurrentInstance().addMessage(null, message);
	}

	private Inventory getInventory() {

		Inventory inventory = new Inventory();

		if (!Strings.isNullOrEmpty(inventoryForm.getId())) {
			inventory.setId(Integer.valueOf(inventoryForm.getId()));
		}

		if (!Strings.isNullOrEmpty(inventoryForm.getGoodsId())) {
			inventory.setGoodsId(Integer.valueOf(inventoryForm.getGoodsId()));
		}

		if (!Strings.isNullOrEmpty(inventoryForm.getCount())) {
			inventory.setCount(Integer.valueOf(inventoryForm.getCount()));
		}

		Timestamp currentDate = DateUtil.getCurrentDateTime();

		inventory.setRgtOpt("Admin");
		inventory.setRgtDate(currentDate);
		inventory.setUpdOpt("Admin");
		inventory.setUpdDate(currentDate);

		return inventory;
	}

	public LazyDataModel<Inventory> getLazyModel() {
		return lazyModel;
	}

	public void setLazyModel(LazyDataModel<Inventory> lazyModel) {
		this.lazyModel = lazyModel;
	}

	public InventoryServiceImpl getInventoryService() {
		return inventoryService;
	}

	public void setInventoryService(InventoryServiceImpl inventoryService) {
		this.inventoryService = inventoryService;
	}

	public InventorySearch getInventorySearch() {
		return inventorySearch;
	}

	public void setInventorySearch(InventorySearch inventorySearch) {
		this.inventorySearch = inventorySearch;
	}

	public InventoryForm getInventoryForm() {
		return inventoryForm;
	}

	public void setInventoryForm(InventoryForm inventoryForm) {
		this.inventoryForm = inventoryForm;
	}

	public CacheDataBean getCacheDataBean() {
		return cacheDataBean;
	}

	public void setCacheDataBean(CacheDataBean cacheDataBean) {
		this.cacheDataBean = cacheDataBean;
	}

}